<template>
    <div>
      <div class="gva-search-box">
        <el-form ref="elSearchFormRef" :inline="true" :model="searchInfo" class="demo-form-inline" :rules="searchRule" @keyup.enter="onSubmit">
          <el-form-item label="影片名" prop="name">
           <el-input v-model="searchInfo.name" placeholder="搜索条件" />
  
          </el-form-item>
             <el-form-item label="合集ID" prop="movieId">
              <el-select v-model="searchInfo.status" clearable placeholder="请选择" @clear="()=>{searchInfo.status=undefined}">
                <el-option v-for="(item,key) in shelvesOptions" :key="key" :label="item.label" :value="item.value" />
              </el-select>
              </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="search" @click="onSubmit">查询</el-button>
            <el-button icon="refresh" @click="onReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="gva-table-box">
          <div class="gva-btn-list">
            <!-- //   btnAuth为权限组件固定写法 .movieAdd  movieAdd为菜单管理中创建的按钮名称 配置过后即可实现对按钮的控制 -->
              <el-button type="primary" icon="plus" @click="openDialog" v-auth="btnAuth.movieAdd">新增</el-button>
              <el-popover v-model:visible="deleteVisible" :disabled="!multipleSelection.length" placement="top" width="160">
              <p>确定要删除吗？</p>
              <div style="text-align: right; margin-top: 8px;">
                  <el-button type="primary" link @click="deleteVisible = false">取消</el-button>
                  <el-button type="primary" @click="onDelete">确定</el-button>
              </div>
              <template #reference>
                  <el-button v-auth="btnAuth.movieDel" icon="delete" style="margin-left: 10px;" :disabled="!multipleSelection.length" @click="deleteVisible = true" >删除</el-button>
              </template>
              </el-popover>
          </div>
          <el-table
          ref="multipleTable"
          style="width: 100%"
          tooltip-effect="dark"
          :data="tableData"
          row-key="ID"
          @selection-change="handleSelectionChange"
          >
          <el-table-column type="selection" width="55" />
          <el-table-column align="left" label="影片名" prop="movieName" width="120" />
          <el-table-column align="left" label="剧集ID" prop="ID" width="120" />
          <el-table-column align="left" label="剧集名称" prop="name" width="120" />
            <el-table-column label="剧集封面" width="150">
                <template #default="scope">
                  <el-image style="width: 100px; height: 140px" :src="getUrl(scope.row.imgFullUrl)" fit="cover"/>
                </template>
            </el-table-column>


          <el-table-column align="left" label="上架状态" prop="status" width="120">
              <template #default="scope">
              {{ filterDict(scope.row.status,shelvesOptions) }}
              </template>
          </el-table-column>

           <el-table-column align="left" label="备注" prop="remarks" width="130"  v-auth="btnAuth.remarksShow" />
          <el-table-column align="left" label="操作" fixed="right" width="140">
              <template #default="scope">
                <el-button type="primary" link icon="edit" class="table-button" @click="watchVideo(scope.row)">预览</el-button>

              <el-button v-auth="btnAuth.episodeEdit" type="primary" link icon="edit" class="table-button" @click="updateSyncEpisodeFunc(scope.row)">同步更新</el-button>
              <!-- <el-button v-auth="btnAuth.episodeDel" type="primary" link icon="delete" @click="deleteRow(scope.row)">删除</el-button> -->
              </template>
          </el-table-column>
          </el-table>
          <div class="gva-pagination">
              <el-pagination
              layout="total, sizes, prev, pager, next, jumper"
              :current-page="page"
              :page-size="pageSize"
              :page-sizes="[10, 30, 50, 100]"
              :total="total"
              @current-change="handleCurrentChange"
              @size-change="handleSizeChange"
              />
          </div>
      </div>
      <el-dialog v-model="dialogFormVisible" :before-close="closeDialog" :title="type==='create'?'添加':'修改'" destroy-on-close>
        <el-scrollbar height="500px">
            <el-form :model="formData" label-position="right" ref="elFormRef" :rules="rule" label-width="140px" class="grid grid-cols-2">
              <el-form-item label="影片名:"  prop="name" >
                <el-input v-model="formData.name" :clearable="true"  placeholder="请输入影片名" />
              </el-form-item>
              <el-form-item label="总集数:"  prop="totalCnt" >
                <el-input v-model.number="formData.totalCnt" :clearable="true" placeholder="请输入总集数" />
              </el-form-item>
              <el-form-item label="最大免费集数:"  prop="maxFreeCnt" >
                <el-input v-model.number="formData.maxFreeCnt" :clearable="true" placeholder="请输入最大免费集数" />
              </el-form-item>
              <el-form-item label="每单集价格:"  prop="price" >
                <el-input v-model.number="formData.price" :clearable="true" placeholder="请输入每单集价格" />
              </el-form-item>
              <el-form-item label="竖版封面:"  prop="imgUrl" >
                  <SelectImage
                   v-model="formData.imgUrl"
                   file-type="image"
                  />
              </el-form-item>
              <el-form-item label="横版封面:"  prop="bannerImgUrl" >
                  <SelectImage
                   v-model="formData.bannerImgUrl"
                   file-type="image"
                  />
              </el-form-item>
              <el-form-item label="作者:"  prop="author" >
                <el-input v-model="formData.author" :clearable="true"  placeholder="请输入作者" />
              </el-form-item>
              <el-form-item label="是否完结:"  prop="fullFlag" >
                <el-select v-model="formData.fullFlag" placeholder="请选择" style="width:100%" :clearable="true" >
                  <el-option v-for="(item,key) in finishStatusOptions" :key="key" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="上架状态:"  prop="status" >
                <el-select v-model="formData.status" placeholder="请选择状态" style="width:100%" :clearable="true" >
                  <el-option v-for="(item,key) in shelvesOptions" :key="key" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>

              <el-form-item label="主角名:"  prop="protagonist" >
                <el-input v-model="formData.protagonist" :clearable="true"  placeholder="请输入主角名" />
              </el-form-item>
              <el-form-item label="备注:"  prop="remarks" >
                <el-input v-model="formData.remarks" :clearable="true"  placeholder="请输入备注" />
              </el-form-item>
              <el-form-item label="标签:"  prop="tag" >
                <el-input v-model="formData.tag" :clearable="true"  placeholder="请输入标签" />
              </el-form-item>
              <el-form-item label="推荐语:"  prop="recommend" >
                <el-input v-model="formData.recommend" :clearable="true"  placeholder="请输入推荐语(12字以内)" type="textarea" :rows="4"  maxlength="12"/>
              </el-form-item>
              <el-form-item label="简介:"  prop="intro" >
                <el-input v-model="formData.intro" :clearable="true"  :rows="4"  placeholder="请输入简介(200字以内)" type="textarea" maxlength="200"/>
              </el-form-item>
            </el-form>
        </el-scrollbar>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="closeDialog">取 消</el-button>
            <el-button type="primary" @click="enterDialog">确 定</el-button>
          </div>
        </template>
      </el-dialog>
  

    </div>
  </template>
  
  <script setup>
  import {
    createEpisode,
    deleteEpisode,
    deleteEpisodeByIds,
    updateEpisode,
    findEpisode,
    getEpisodeList
  } from '@/api/episode'
  import { getUrl } from '@/utils/image'
  // 图片选择组件
  import SelectImage from '@/components/selectImage/selectImage.vue'
  
  // 生成推广链接组件
  import ReferralForm from '@/view/tReferral/tReferralForm.vue'
  
  // 全量引入格式化工具 请按需保留
  import { getDictFunc, formatDate, formatBoolean, filterDict, ReturnArrImg, onDownloadFile } from '@/utils/format'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { ref, reactive } from 'vue'
  
  //引用菜单按钮权限组件
  import { useBtnAuth } from '@/utils/btnAuth'
      const btnAuth = useBtnAuth()
  
  defineOptions({
      name: 'MovieAuto'
  })
  
  // 自动化生成的字典（可能为空）以及字段
  const finishStatusOptions = ref([])
  const shelvesOptions = ref([])
  const formData = ref({
          name: '',
          imgUrl: "",
          bannerImgUrl: "",
          author: '',
          totalCnt: '',
          maxFreeCnt: '',
          price: '',
          fullFlag: 1,
          cpId: 0,
          cpUpdateTime: new Date(),
          protagonist: '',
          tag: '',
          intro: '',
          recommend: '',
          remarks: '',
          status: 2,
          firstSid: 0,
          latestEpisode: '',
          createUid: 0,
          createTime: new Date(),
          updateUid: 0,
          updateTime: new Date(),
          })
  
  const moviePriceMinMax =  (rule, value, callback) => {
    if(value>350|| value<10) {
      callback('超出限制')
    } else {
      callback()
    }
  }
  const movieTotalCntMinMax =  (rule, value, callback) => {
    if(value>500|| value<=0) {
      callback('超出限制')
    } else {
      callback()
    }
  }
  
  // 验证规则
  const rule = reactive({
                 name : [{
                     required: true,
                     message: '',
                     trigger: ['input','blur'],
                 },
                 {
                     whitespace: true,
                     message: '不能只输入空格',
                     trigger: ['input', 'blur'],
                }
                ],
                 imgUrl : [{
                     required: false,
                     message: '',
                     trigger: ['input','blur'],
                 },
                ],
                 maxFreeCnt : [{
                     required: true,
                     message: '',
                     trigger: ['input','blur'],
                 },
                ],
                 price : [{ 
                    validator: moviePriceMinMax, 
                    message: '单集价格范围10-350',
                    trigger: 'blur'
                  },
                  {type: 'number', message: '请输入数字', trigger: 'blur'}
                ],
                totalCnt : [{
                    validator: movieTotalCntMinMax, 
                      message: '总集数范围1~500',
                      trigger: 'blur'
                 },
                 {type: 'number', message: '请输入数字', trigger: 'blur'}
                ],
                fullFlag : [{
                     required: true,
                     message: '请选择连载状态',
                     trigger: ['input','blur'],
                 },
                ],
                status : [{
                     required: true,
                     message: '请选择上下架状态',
                     trigger: ['input','blur'],
                 },
                ],
  })
  
  const searchRule = reactive({
    createdAt: [
      { validator: (rule, value, callback) => {
        if (searchInfo.value.startCreatedAt && !searchInfo.value.endCreatedAt) {
          callback(new Error('请填写结束日期'))
        } else if (!searchInfo.value.startCreatedAt && searchInfo.value.endCreatedAt) {
          callback(new Error('请填写开始日期'))
        } else if (searchInfo.value.startCreatedAt && searchInfo.value.endCreatedAt && (searchInfo.value.startCreatedAt.getTime() === searchInfo.value.endCreatedAt.getTime() || searchInfo.value.startCreatedAt.getTime() > searchInfo.value.endCreatedAt.getTime())) {
          callback(new Error('开始日期应当早于结束日期'))
        } else {
          callback()
        }
      }, trigger: 'change' }
    ],
  })
  
  const elFormRef = ref()
  const elSearchFormRef = ref()
  
  // =========== 表格控制部分 ===========
  const page = ref(1)
  const total = ref(0)
  const pageSize = ref(10)
  const tableData = ref([])
  const searchInfo = ref({})
  
  // 重置
  const onReset = () => {
    searchInfo.value = {}
    getTableData()
  }
  
  // 搜索
  const onSubmit = () => {
    elSearchFormRef.value?.validate(async(valid) => {
      if (!valid) return
      page.value = 1
      pageSize.value = 10
      getTableData()
    })
  }
  
  // 分页
  const handleSizeChange = (val) => {
    pageSize.value = val
    getTableData()
  }
  
  // 修改页面容量
  const handleCurrentChange = (val) => {
    page.value = val
    getTableData()
  }
  
  // 查询
  const getTableData = async() => {
    const table = await getEpisodeList({ page: page.value, pageSize: pageSize.value, ...searchInfo.value })
    if (table.code === 0) {
      tableData.value = table.data.list
      total.value = table.data.total
      page.value = table.data.page
      pageSize.value = table.data.pageSize
    }
  }
  
  getTableData()
  
  // ============== 表格控制部分结束 ===============
  
  // 获取需要的字典 可能为空 按需保留
  const setOptions = async () =>{
      finishStatusOptions.value = await getDictFunc('finishStatus')
      shelvesOptions.value = await getDictFunc('shelves')
  }
  
  // 获取需要的字典 可能为空 按需保留
  setOptions()
  
  
  // 多选数据
  const multipleSelection = ref([])
  // 多选
  const handleSelectionChange = (val) => {
      multipleSelection.value = val
  }
  
  // 删除行
  const deleteRow = (row) => {
      ElMessageBox.confirm('确定要删除吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
      }).then(() => {
              deleteMovieAutoFunc(row)
          })
      }
  
  
  // 批量删除控制标记
  const deleteVisible = ref(false)
  
  // 多选删除
  const onDelete = async() => {
        const ids = []
        if (multipleSelection.value.length === 0) {
          ElMessage({
            type: 'warning',
            message: '请选择要删除的数据'
          })
          return
        }
        multipleSelection.value &&
          multipleSelection.value.map(item => {
            ids.push(item.ID)
          })
        const res = await deleteMovieAutoByIds({ ids })
        if (res.code === 0) {
          ElMessage({
            type: 'success',
            message: '删除成功'
          })
          if (tableData.value.length === ids.length && page.value > 1) {
            page.value--
          }
          deleteVisible.value = false
          getTableData()
        }
      }
  
  // 行为控制标记（弹窗内部需要增还是改）
  const type = ref('')
  
  // 更新行
  
  
  // 删除行
  const deleteMovieAutoFunc = async (row) => {
      const res = await deleteMovieAuto({ ID: row.ID })
      if (res.code === 0) {
          ElMessage({
                  type: 'success',
                  message: '删除成功'
              })
              if (tableData.value.length === 1 && page.value > 1) {
              page.value--
          }
          getTableData()
      }
  }
  

  // 弹窗控制标记
  const dialogFormVisible = ref(false)
  
  
  // 查看详情控制标记
  const detailShow = ref(false)
  
  
  // 打开详情弹窗
  const openDetailShow = () => {
    detailShow.value = true
  }
  
  
  // 打开详情
  const getDetails = async (row) => {
    // 打开弹窗
    const res = await findMovieAuto({ ID: row.ID })
    if (res.code === 0) {
      formData.value = res.data.removie
      openDetailShow()
    }
  }
  
  
  // 关闭详情弹窗
  const closeDetailShow = () => {
    detailShow.value = false
    formData.value = {
            name: '',
            author: '',
            totalCnt: 0,
            maxFreeCnt: 0,
            price: 0,
            fullFlag: undefined,
            cpId: 0,
            cpUpdateTime: new Date(),
            protagonist: '',
            tag: '',
            intro: '',
            recommend: '',
            remarks: '',
            status: undefined,
            firstSid: 0,
            latestEpisode: '',
            createUid: 0,
            createTime: new Date(),
            updateUid: 0,
            updateTime: new Date(),
            }
  }
  
  
  // 打开弹窗
  const openDialog = () => {
      type.value = 'create'
      dialogFormVisible.value = true
  }
  
  // 关闭弹窗
  const closeDialog = () => {
      dialogFormVisible.value = false
      formData.value = {
          name: '',
          author: '',
          totalCnt: 0,
          maxFreeCnt: 0,
          price: 0,
          fullFlag: undefined,
          cpId: 0,
          cpUpdateTime: new Date(),
          protagonist: '',
          tag: '',
          intro: '',
          recommend: '',
          remarks: '',
          status: undefined,
          firstSid: 0,
          latestEpisode: '',
          createUid: 0,
          createTime: new Date(),
          updateUid: 0,
          updateTime: new Date(),
          }
  }
  // 弹窗确定
  const enterDialog = async () => {
       elFormRef.value?.validate( async (valid) => {
               if (!valid) return
                let res
                switch (type.value) {
                  case 'create':
                    res = await createMovieAuto(formData.value)
                    break
                  case 'update':
                    res = await updateMovieAuto(formData.value)
                    break
                  default:
                    res = await createMovieAuto(formData.value)
                    break
                }
                if (res.code === 0) {
                  ElMessage({
                    type: 'success',
                    message: '创建/更改成功'
                  })
                  closeDialog()
                  getTableData()
                }
        })
  }

  // 同步更新视频处理-操作
const updateSyncEpisodeFunc = (row) => {
    ElMessageBox.confirm('确定要同步更新吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
      SyncEpisodeFunc(row)
        })
    }
// 同步更新视频处理
const SyncEpisodeFunc = async (row) => {
    const res = await syncEpisode({ ID: row.ID})
    if (res.code === 0) {
        ElMessage({
                type: 'success',
                message: '操作成功'
            })
        getTableData()
    }else{
        ElMessage({
                  type: 'error',
                  message: res.msg
              })
    }
}
  </script>
  
  <style>
  
  </style>
  